package cn.tedu.boot23.controller;

import cn.tedu.boot23.entity.Hero;
import cn.tedu.boot23.utils.DBUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.*;

@Controller
public class HeroController {
    @RequestMapping("/add")
    @ResponseBody
    public String add(Hero hero){
        System.out.println("hero = " + hero);
        //获取连接
        try (Connection conn = DBUtils.getConn()){
            String sql = "insert into hero values(null,?,?,?)";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,hero.getName());
            ps.setString(2,hero.getType());
            ps.setInt(3,hero.getMoney());
            //执行SQL语句
            ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "添加完成!";
    }

    @RequestMapping("/select")
    @ResponseBody
    public String select(){
        String html="<table border=\"1\">\n" +
                "    <caption>英雄列表</caption>\n" +
                "    <tr>\n" +
                "        <th>id</th>\n" +
                "        <th>姓名</th>\n" +
                "        <th>类型</th>\n" +
                "        <th>价格</th>\n" +
                "    </tr>\n";
        try (Connection conn=DBUtils.getConn()){
            String sql="select *from hero";
            Statement s=conn.createStatement();
            ResultSet rs=s.executeQuery(sql);
            while (rs.next()){
                int id=rs.getInt(1);
                String name=rs.getString(2);
                String type=rs.getString(3);
                int money=rs.getInt(4);
                html+="<tr>";
                html+="<td>"+id+"</td>";
                html+="<td>"+name+"</td>";
                html+="<td>"+type+"</td>";
                html+="<td>"+money+"</td>";
                html+="</tr>";
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        html+="</table>";
        return html;
    }

}
